import json

from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django import http
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout, mixins
from django.db import DatabaseError
from django.contrib.auth.decorators import login_required

import re

from .models import User, Address
# from .utils import UsernameMobileAuthBackend
import logging
from meiduo_mall.utils.response_code import RETCODE
from celery_tasks.email.tasks import send_verify_email
from .utils import generate_verify_email_url, check_token_to_user


logger = logging.getLogger('django') # 创建日志输出器对象

# Create your views here.

class RegisterViev(View):
    """
    注册页面展示
    """
    def get(self,request):

        return render(request, 'register.html')


# 接收前端传入的表单数据，有密码隐私,post请求
# < input type = "text" name = "sms_code" id = "msg_code" class ="msg_input" v-model="sms_code"
    #传入的参数username password password2 mobile allow, 在input标签的name属性里
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code = request.POST.get('sms_code')
        allow = request.POST.get('allow')
# 校验数据是否正确有效，前端有校验，后端也必须要校验，可能是通过postman传过来
        if not all([username, password, password2, mobile, sms_code, allow]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        if not re.match(r'[a-zA-Z0-9]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        if password2 != password:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('输入11位正确的手机号')
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        #  短信验证码验证
        redis_conn = get_redis_connection('verify_code')
        sms_code_sever = redis_conn.get('sms_%s' % mobile)

        if sms_code_sever is None or sms_code != sms_code_sever.decode():
            # return http.HttpResponseForbidden('短信验证码有误')

            return render(request, 'register.html', {"register_errmsg": '验证码有误'})

# 保存数据到数据库，即创建一个模型类对象
        #user = models.User(username=username, password=password, mobile=mobile)
        #  需要使用模型类.objects.create()方法创建，这里 create_user() 方法中封装了 set_password() 方法加密密码。
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError as e:
            logger.error(e)
            return render(request, 'register.html', {"register_errmsg": '注册失败'})


# 登入用户，状态保持
        login(request, user)
# 响应返回后端, 这里重定向到首页
        # return render(request, 'index.html')    # 可以跳到主业

        # 首页用户名展示 设置用户名保存到cookie
        response = redirect('/')
        response.set_cookie('username', user.username, max_age=60*60*24*14)
        return response


class UsernameCountView(View):
    def get(self, request, username):

        count = User.objects.filter(username=username).count()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK','count': count})


class MobileCountView(View):
    def get(self, request, mobile):

        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK','count': count})


class LoginView(View):
    # 先get访问login页面，响应login页面给浏览器
    def get(self,request):
        return render(request, 'login.html')

    # 再post表单请求
    def post(self,request):
        # 提取参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # 校验参数
        if all([username, password]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名或手机号')

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')

        # 认证 ,也就是通过用户名到SQL取得user,再对比密码,注意sql的密码是加密的.
        # user = User.objects.get(username=username)
        # user.check_password(password)
        # 可以使用django提供的方法
        # UsernameMobileAuthBackend.authenticate(username=username, password=password)
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        # 登陆状态保持
        login(request, user)
        # 不勾选记住登陆
        if remembered != 'on':  # checkbox单选框，勾选 on , 不勾选 None
            #0,用户session的Cookie将在用户的浏览器关闭时过期，
            # none使用默认的值，默认为两周，可以通过在settings.py中设置SESSION_COOKIE_AGE来设置全局默认值。
            request.session.set_expiry(111)
        else:
            request.session.set_expiry(None)
        # 返回响应结果
        # 获取来源next参数, 没有的话返回首页

        response = redirect(request.GET.get('next', '/'))
        # 首页用户名展示
        response.set_cookie('username', user.username, max_age=60 * 60 * 24 * 14)
        return response


class LogoutView(View):

    def get(self,request):
        # 退出登陆，即删除session
        logout(request)
        # 重定向到登陆页
        # response = redirect('/login/')
        # 使用反解析
        response = redirect(reverse('users:login'))
        # 删除cookie的username
        response.delete_cookie('username')
        return response


class UserInfoView(mixins.LoginRequiredMixin, View):
    def get(self,request):
        # 获取用户,user可能是登陆用户的user,有可能是未登陆的匿名用户.
        # user = request.user
        # user.is_authenticated为True,匿名.user.is_authent icated为false
        # if user.is_authenticated:
        #     return render(request, 'user_center_info.html')
        # else:
        #     # 记住重定向的来源,urls传参
        #     return redirect('/login/?next=/info/')

        # let username = "{{ request.user.username }}";
        # 前端修改，或者后端传入context={'username': 'request.user.username'}

        return render(request, 'user_center_info.html')


class EmailView(mixins.LoginRequiredMixin,View):
    def put(self, request):
        # 提取数据 put data是通过body传过来的
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验
        if all([email]) is False:
            return http.HttpResponseForbidden('缺少邮箱数据')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('邮箱格式不正确')

        # 处理， 保存
        user = request.user # 选中当期用户
        user.email = email  # 给用户的email字段设置值
        user.save()     # 保存

        # # 在此地还要发送一个邮件到email
        # from django.core.mail import send_mail
        # # send_mail(邮件主题, 普通邮件正文, 发件人邮箱, [收件人邮件], html_message='超文本邮件内容')
        # send_mail('美多', '', '美多商城<itcast99@163.com>', [email], html_message='收钱了')
        # 调用加密生成的url
        verify_url = generate_verify_email_url(user)
        send_verify_email.delay(email, verify_url)
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class VerifyEmailView(View):
    """激活邮箱"""
    def get(self,request):
        """实现邮箱激活逻辑"""
        # 获取参数
        token = request.GET.get('token')
        # 解密并获取到user
        user = check_token_to_user(token)

        if user is None:
            return http.HttpResponseForbidden('无效的token')

        # 修改user的active_email字段为true
        user.email_active = True
        user.save()
        return redirect('/info/')


class AddressView(mixins.LoginRequiredMixin, View):
    """提供收货地址界面"""
    def get(self, request):
        # 获取当前用户的所有收货地址
        user = request.user
        address_qs = Address.objects.filter(user=user, is_deleted=False)
        address_list = []
        for address in address_qs:
            address_dict = {
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province_id': address.province_id,
                'province': address.province.name,
                'city_id': address.city_id,
                'city': address.city.name,
                'district_id': address.district_id,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email,
            }
            address_list.append(address_dict)
        context = {
            'addresses': address_list,
            'default_address_id': user.default_address_id
        }

        return render(request, 'user_center_site.html', context)


class CreateAddressView(mixins.LoginRequiredMixin, View):
    """新增收货地址"""
    def post(self, request):
        # 判断是否超过地址个数上限20
        user = request.user
        # count = Address.objects.filter(user=user).count()
        count = user.addresses.count()

        if count >= 20:
            return http.HttpResponseForbidden('用户收货地址上限')

        # 提取参数
        json_dict = json.loads(request.body.decode()) # json数据提取成字典数据
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')


        # 保存新增收货地址，创建address对象保存到mysql
        try:
            address = Address.objects.create(
                user=user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            if user.default_address is None:
                user.default_address = address
                user.save()
        except Exception:
            return http.HttpResponseForbidden('新增地址出错')
        # 把新增的地址数据响应回去
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        # return
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})


class UpdateDestroyAddressView(mixins.LoginRequiredMixin, View):
    """修改和删除收货地址"""
    def put(self, request, address_id):
        """修改收货地址"""
        # 获取需要修改的地址对象
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('修改地址有误')

        # 提取参数
        json_dict = json.loads(request.body.decode())  # json数据提取成字典数据
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 修改收货地址信息
        Address.objects.filter(id=address_id).update(
            title=title,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        address = Address.objects.get(id=address_id)    # 要重新查询一次新数据
        # 把新增的地址数据响应回去
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        # return
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})

    def delete(self, request, address_id):
        """删除收货地址"""
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('删除的地址不存在')

        address.is_deleted = True
        address.save()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class DefaultAddressView(mixins.LoginRequiredMixin, View):
    """设置默认地址"""
    def put(self, request, address_id):

        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('无效的收货地址')

        user = request.user
        user.default_address_id = address_id
        user.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class UpdateTitleAddressView(mixins.LoginRequiredMixin, View):
    """修改用户收货地址标题"""
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('无效的收货地址')

        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        address.title = title
        address.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class ChangePasswordView(mixins.LoginRequiredMixin, View):
    """修改密码"""
    def get(self, request):
        """展示修改密码页面"""

        return render(request, 'user_center_pass.html')

    def post(self, request):
        # 提取参数
        old_password = request.POST.get('old_pwd')
        password = request.POST.get('new_pwd')
        password2 = request.POST.get('new_cpwd')

        # 校验
        if all([old_password, password, password2]) is False:
            return http.HttpResponseForbidden("缺少必传参数")

        user = request.user
        if user.check_password(old_password) is False:
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        # 修改密码
        user.set_password(password)
        user.save()

        # 响应重定向到登陆页面
        logout(request)
        response = redirect('/login/')
        response.delete_cookie('username')

        return response


class UserBrowseHistory(View):
    """用户商品浏览记录"""
    def post(self, request):
        pass





















